﻿using System;
using System.Reactive.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Bull.Core.AttachedBehaviours {
    public static class PasswordBoxAttachedBehaviour {
        public static readonly DependencyProperty PasswordProperty =
            DependencyProperty.RegisterAttached("Password", typeof(string), typeof(PasswordBoxAttachedBehaviour), new PropertyMetadata(string.Empty,
                (sender, e) =>
                {
                    var passwordBox = sender as PasswordBox;
                    if (passwordBox == null)
                        return;

                    var binding = passwordBox.GetBindingExpression(PasswordProperty);
                    if (binding == null)
                        return;
                    
                    var prop = passwordBox.DataContext.GetType().GetProperty(binding.ResolvedSourcePropertyName);
                    Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
                        handler => passwordBox.PasswordChanged += handler,
                        handler => passwordBox.PasswordChanged -= handler)
                        .Select(item => item.EventArgs)
                        .Subscribe(result => prop.SetValue(passwordBox.DataContext, passwordBox.Password));
                }));

        public static string GetPassword(PasswordBox sender) {
            return (string)sender.GetValue(PasswordProperty);
        }

        public static void SetPassword(PasswordBox sender, string value) {
            sender.SetValue(PasswordProperty, value);
        }
    }
}
